package com.taoye.thread;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;

/**
 * join方法和sleep方法的区别
 *
 * @author : Mr.Tao
 * @version : 1.0
 * @date : 2022/4/4 10:31
 **/
public class Demo46 {
    public static void main(String[] args) throws InterruptedException {
        Demo46ThreadA t = new Demo46ThreadA();
        t.setName("A");
        Thread t2 = new Demo46ThreadB(t);
        t2.setName("B");
        Thread t3 = new Demo46ThreadC(t);
        t3.setName("C");
        t2.start();
        //为了预防t3先拿到锁执行完毕，先睡眠一下确保t2先执行
        Thread.sleep(200);
        t3.start();
    }
}


class Demo46ThreadA extends Thread {

    @Override
    public void run() {
        try {
            System.out.println("我是线程" + Thread.currentThread().getName() + "，开始时间：" + DateUtil.now());
            Thread.sleep(2000);
            System.out.println("我是线程" + Thread.currentThread().getName() + "，结束时间：" + DateUtil.now());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 这里不是静态方法，使用的锁跟对象锁是同一个锁
     */
    synchronized public void fun() {
        try {
            Thread.sleep(2000);
            System.out.println("fun方法执行时间:" + DateUtil.now());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Demo46ThreadB extends Thread {
    private Demo46ThreadA t;

    public Demo46ThreadB(Demo46ThreadA t) {
        this.t = t;
    }

    @Override
    public void run() {
        synchronized (t) {
            try {
                System.out.println("我是线程" + Thread.currentThread().getName() + "，开始时间：" + DateUtil.now());
                t.start();
                //使用sleep方法会阻塞
                //Thread.sleep(3000);
                //使用join方法会释放锁
                t.join();
                System.out.println("我是线程" + Thread.currentThread().getName() + "，开始执行耗时操作" + DateUtil.now());
                //模拟耗时操作
                for (int i = 0; i < Integer.MAX_VALUE; i++) {
                    String s = new String();
                    String s1 = RandomUtil.randomString(9);
                }
                System.out.println("我是线程" + Thread.currentThread().getName() + "，结束时间：" + DateUtil.now());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

class Demo46ThreadC extends Thread {
    private Demo46ThreadA t;

    public Demo46ThreadC(Demo46ThreadA t) {
        this.t = t;
    }

    @Override
    public void run() {
        System.out.println("我是线程" + Thread.currentThread().getName() + "，开始时间：" + DateUtil.now());
        t.fun();
        System.out.println("我是线程" + Thread.currentThread().getName() + "，结束时间：" + DateUtil.now());
    }
}